package com.rockymew.core.utility.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class UrlUtils {
    
    /**
     * 构建请求参数字符串, 不含有?
     * @param <T>
     * @param params
     * @return
     * @throws UnsupportedEncodingException
     */
    public static <T> String buildQueryString( Map<String, T> params) throws UnsupportedEncodingException{
        StringBuffer paramExt = new StringBuffer(1000);
        
        if( null != params && params.size() > 0  ){
            boolean bfirst = true;
            for (Map.Entry<String, T> entry : params.entrySet()) {
                String key = entry.getKey();
                if( null == key ){
                    continue;
                }
                
                String value = ( null == entry.getValue() ? "" : entry.getValue().toString() );
                String kv = String.format("%s%s=%s",
                        bfirst ? "" : "&",
                                URLEncoder.encode(key, "UTF-8"),
                                URLEncoder.encode(value, "UTF-8")
                );
                paramExt.append(  kv  );
                bfirst = false;
            }
        }
        return paramExt.toString();
    }
    
    public static String getFullURL(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String queryString = request.getQueryString();

        if ( queryString == null || queryString.isEmpty() ) {
            return requestURL.toString();
        } else {
            return requestURL.append('?').append(queryString).toString();
        }
    }
    
    public static String getFullURLForWxJsSignature(HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        String queryString = request.getQueryString();

        if ( queryString == null || queryString.isEmpty() ) {
            return requestURL.toString();
        } else {
            return requestURL.append('?').append(queryString).toString();
        }
    }

}
